﻿using System;
using System.Threading.Tasks;
using MassTransit.Courier;
using Microsoft.Extensions.Logging;

namespace MassTransitDemo.OrderService.Activities.CreateOrder
{
    public class ReduceStockActivity : IActivity<ReduceStockModel, ReduceStockLog>
    {
        private readonly ILogger<ReduceStockActivity> logger;

        public ReduceStockActivity(ILogger<ReduceStockActivity> logger)
        {
            this.logger = logger;
        }

        public async Task<ExecutionResult> Execute(ExecuteContext<ReduceStockModel> context)
        {
            var argument = context.Arguments;
            logger.LogInformation($"扣减库存-{DateTime.Now.ToString("HH:mm:ss")}");
            await Task.Delay(100);
            // httpClient
            return context.Completed(new ReduceStockLog() { ProductId = argument.ProductId, Amount = 1 });
        }

        public async Task<CompensationResult> Compensate(CompensateContext<ReduceStockLog> context)
        {
            logger.LogWarning($"增加库存-{DateTime.Now.ToString("HH:mm:ss")}");
            await Task.Delay(100);
            // httpClient
            return context.Compensated();
        }
    }

    public class ReduceStockModel
    {
        public string ProductId { get; set; }
    }

    public class ReduceStockLog
    {
        public string ProductId { get; set; }
        public int Amount { get; set; }
    }
}
